//
//  PreviewSeatsViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/11/13.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "ZZLayout.h"
#import "TypeMenu.h"

#import "TT_ShareManager.h"
#import "SeatsListNaviView.h"
#import "SeatsListBottomView.h"

#import "PreviewSeatsHeaderView.h"

#import "SearchKeyWordItemCell.h"

#import "SeatsListHeaderReusableView.h"
#import "SeatsListFooterReusableView.h"

#import "PreviewSeatsViewController.h"

@interface PreviewSeatsViewController ()
<ZZLayoutDelegate,
UITextFieldDelegate,
UICollectionViewDelegate,
UICollectionViewDataSource>

/**页面主视图*/
@property (nonatomic , strong) UICollectionView *collectionView;
@property (nonatomic , strong) PreviewSeatsHeaderView *headView;

@property (nonatomic,strong)TypeMenu *typeMenu;

@property (nonatomic, strong) NSMutableArray <UIImage *>*images;

@property (nonatomic, strong) NSMutableArray <CommonSeatsModel *>*dataArray;

@end

@implementation PreviewSeatsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self request_seats];
}

- (void)initView {
        
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:UIColorHex(0x666666) forState:UIControlStateNormal];

    [rightBtn setImage:[UIImage imageNamed:@"more_icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.frame = CGRectMake(0,0,40,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItems =@[rightItem];
    
    [self.view addSubview:self.collectionView];
    
    self.headView = [[NSBundle mainBundle] loadNibNamed:@"PreviewSeatsHeaderView"owner:nil options:nil].firstObject;
    self.headView.frame = CGRectMake(0, -TTScreenWidth*0.61, TTScreenWidth, TTScreenWidth*0.61);
    self.headView.searchTF.delegate = self;
    [self.collectionView addSubview:self.headView];
    self.collectionView.contentInset = UIEdgeInsetsMake(TTScreenWidth * 0.61, 0, 0, 0);
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self initViewAction];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [self request_seats];
    return YES;
}

- (void)initViewAction {
    
    WEAKSELF
    self.typeMenu.selectRowBlcok = ^(NSString * _Nonnull title) {
        NSLog(@"%@",title);
        if ([title isEqualToString:@"分享"]) {
            [weakSelf shareAction];
        } else if ([title isEqualToString:@"下载"]) {
            [weakSelf jietu];
        }
    };
    
}

- (void)moreAction {
    [self.typeMenu showMenu];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)shareAction {
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?userName=%@&nickName=%@",BA_GlobalH5_Domain,@"/weddingSeats",[TTUserModel sharedObject].username,[Utilities stringToUnicode:[TTUserModel sharedObject].nickname]];
    model.title = [NSString stringWithFormat:@"%@婚宴席位表",[TTUserModel sharedObject].nickname];
    model.content = @"已为您安排好席位，请查看您的席位表，欢迎您的到来";
    model.image = [UIImage imageNamed:@"ba_logo"];
    [[TT_ShareManager share] callShareViewWithModel:model];
}

//截长图关键代码
- (void)jietu {
    //回到顶部
    //截图-加入数组-判断能不能滑动-截图-加入数组-判断能不能滑动。。。。。。。。。
    [self.collectionView scrollToTop];
    
    self.images = @[].mutableCopy;
    //总高除以一屏显示高  算出页数
    NSInteger pageCount = self.collectionView.contentSize.height/self.collectionView.maxY + 1;
    for (int i = 0; i < pageCount; i++) {
        
        [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.maxY * i)];
        UIImage *imgv = [self nomalSnapshotImage];

        [self.images addObject:imgv];
        sleep(0.5);
    }
    

    NSLog(@"%@",self.images);
    UIImage *tempImage = self.images.firstObject;
    UIImage *resultImage;
    for (int i = 1; i < self.images.count; i++) {
        tempImage = [self addSlaveImage:self.images[i] toMasterImage:tempImage];
    }
    resultImage = tempImage;
    UIImageWriteToSavedPhotosAlbum(resultImage, nil, nil, nil);

    [SVProgressHUD showSuccessWithStatus:@"下载成功，请去相册查看"];
    [SVProgressHUD dismissWithDelay:1];

}


- (UIImage *)addSlaveImage:(UIImage *)slaveImage toMasterImage:(UIImage *)masterImage {
    CGSize size;
    size.width = masterImage.size.width;
    size.height = masterImage.size.height + slaveImage.size.height;
    
    UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
    
    //Draw masterImage
    [masterImage drawInRect:CGRectMake(0, 0, masterImage.size.width, masterImage.size.height)];
    
    //Draw slaveImage
    [slaveImage drawInRect:CGRectMake(0, masterImage.size.height, masterImage.size.width, slaveImage.size.height)];
    
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return resultImage;
}

- (UIImage *)nomalSnapshotImage
{
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, [UIScreen mainScreen].scale);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

#pragma mark- 协议方法
//collectionView的协议方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchKeyWordItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchKeyWordItemCellID" forIndexPath:indexPath];
    cell.itemTitleLab.text = self.dataArray[indexPath.section].userSeatList[indexPath.row].name;
    cell.itemTitleLab.backgroundColor = UIColorHex(0xffffff);
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray[section].userSeatList.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头

    if (kind == UICollectionElementKindSectionHeader) {
        SeatsListHeaderReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SeatsListHeaderReusableView" forIndexPath:indexPath];
        
//        if ([self.dataArray[indexPath.section].isMainTable isEqualToString:@"1"]) {
//            headerView.seatsTitleLab.text = @"主桌";
//        } else {
//
//            if (self.dataArray[indexPath.section].seatsName.length > 0) {
                headerView.seatsTitleLab.text = self.dataArray[indexPath.section].seatsName;
//            } else {
//                headerView.seatsTitleLab.text = [NSString stringWithFormat:@"%ld桌",(long)indexPath.section];
//            }
//        }
        
        headerView.seatsCountLab.text = [NSString stringWithFormat:@"%@/%@座位已安排",self.dataArray[indexPath.section].number,self.dataArray[indexPath.section].seatsNumber];

        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];

        
        reusableView = footerView;
    }
    return reusableView;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的度
    return 30;//同一section下请不要改变高度.
}

- (CGFloat)layout:(ZZLayout *)layout widthForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的宽

    if (self.dataArray.count > indexPath.section && self.dataArray[indexPath.section].userSeatList.count > indexPath.row) {
        return self.dataArray[indexPath.section].userSeatList[indexPath.row].itemWidth;//这里可以根据内容传入任意宽度
    }
    return CGFLOAT_MIN;//这里可以根据内容传入任意宽度
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距
    return 5;
}

- (CGFloat) layout:(ZZLayout *)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距
    return 5;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度
    return CGSizeMake(self.view.bounds.size.width, 86);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾部的高度
    return CGSizeMake(self.view.bounds.size.width, 10);
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {
    return [UIColor whiteColor];
}

#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeAutomateFloat delegate:self];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - kStatusBarHeight - NavBar_Height) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColorHex(0xf8f8f8);
        
        //注册cell
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchKeyWordItemCell" bundle:nil] forCellWithReuseIdentifier:@"SearchKeyWordItemCellID"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"SeatsListHeaderReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SeatsListHeaderReusableView"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];

        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _collectionView;
}

- (TypeMenu *)typeMenu{
    if (!_typeMenu) {
        NSArray *dataArray = [[NSArray alloc]initWithObjects:
           [NSDictionary dictionaryWithObjectsAndKeys:@"分享",@"title",@"",@"img", nil],
           [NSDictionary dictionaryWithObjectsAndKeys:@"下载",@"title",@"",@"img", nil],nil];
        _typeMenu = [TypeMenu createMenuWithFrame:CGRectMake(TTScreenWidth - 130, kStatusBarHeight + NavBar_Height - 10 , 120, 100) dataArray:dataArray];
    }
    return _typeMenu;
}

- (void)request_seats {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.headView.searchTF.text forKey:@"name"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MarrySeatsPage];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSArray *list = [data valueForKey:@"data"];
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    weakSelf.dataArray = @[].mutableCopy;
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *dic = list[i];
                        CommonSeatsModel *model = [CommonSeatsModel modelWithDictionary:dic];
                        
                        model.userSeatList = @[].mutableCopy;
                        NSArray *userSeatList = [dic valueForKey:@"userSeatList"];
                        if ([userSeatList isKindOfClass:[NSArray class]]) {
                            
                            for (int j = 0; j < userSeatList.count; j++) {
                                NSDictionary *seatDic = userSeatList[j];
                                
                                CommonUserSeatsModel *seatModel = [CommonUserSeatsModel modelWithDictionary:seatDic];
                                seatModel.itemWidth = [Utilities getStringWidthWithString:seatModel.name fontSize:14 andHeight:30];
                                [model.userSeatList addObject:seatModel];
                            }
                        }
                        [weakSelf.dataArray addObject:model];
                    }
                }
                [weakSelf.collectionView reloadData];

            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}

@end
